package com.a3dweijing.wetouch2.network;

import com.a3dweijing.wetouch2.R;
import com.a3dweijing.wetouch2.base.App;
import com.a3dweijing.wetouch2.constant.Api;

import java.io.File;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2018/3/21.
 */

public class RetrofitUtil {
    private static RetrofitUtil mInstance;
    private static final byte[] LOCKER = new byte[0];
    private static String baseUrl = App.getmContext().getResources().getString(R.string.remote_host) + "/";
    private static String baseUrlphp = App.getmContext().getResources().getString(R.string.remote_of_php) + "/";
    private final Retrofit retrofit;
    private final Retrofit retrofitofphp;


    public static RetrofitUtil getInstance() {
        if (mInstance == null) {
            synchronized (LOCKER) {
                if (mInstance == null) {
                    mInstance = new RetrofitUtil();
                }
            }
        }
        return mInstance;
    }

    RetrofitUtil() {
        retrofit = new Retrofit.Builder()
                //设置OKHttpClient
                .client(OKHTTPUtil.getInstance().mOkHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                //baseUrl
                .baseUrl(baseUrl)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        retrofitofphp = new Retrofit.Builder()
                //设置OKHttpClient
                .client(OKHTTPUtil.getInstance().mOkHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                //baseUrl
                .baseUrl(baseUrlphp)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    public Api getApi() {
        Api api = retrofit.create(Api.class);
        return api;
    }

    public Api getApiOfPhp() {
        Api api = retrofitofphp.create(Api.class);
        return api;
    }

    /**
     * 长传文件
     *
     * @param name
     * @param file
     * @return
     */
    public MultipartBody.Part getBodyByFile(String name, File file) {
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part headFile = MultipartBody.Part.createFormData(name, file.getName(), requestFile);
        return headFile;
    }

    /**
     * 上传文件带参数
     * @param name
     * @param v
     * @return
     */
    public MultipartBody.Part getBodyByDate(String name, String v) {
        return MultipartBody.Part.createFormData(name, v);
    }

    public RequestBody getBodyBuDate(String s)
    {
      return RequestBody.create(okhttp3.MediaType.parse("text/plain"), s);
    }
}
